package Gap;

import Envelopes.Envelopes_v01;
import JChamp.Bobsley_v01;
import JChamp.MaRsiStoch_v01;

import com.dukascopy.api.system.*;
import com.dukascopy.api.system.ITesterClient.InterpolationMethod;
import com.dukascopy.api.*;
import com.dukascopy.calculator.Base;

import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.io.*;

import martin.Martin_v05;
import nimy_v01.Nimy_v03;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

public class MyTesterMain {
	private static final Logger LOGGER = LoggerFactory.getLogger ( MyTesterMain.class );
	
	  //url of the DEMO jnlp
	  private static String   jnlpUrl   = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
	  private static String   userName  = "DEMO3qBxzQ";
	  private static String   password  = "qBxzQ";
	  private static long     testPID   = -1;
	  
	  private static ITesterClient testClient;

	  public static void main ( String[] args )	
	          throws Exception {
	    //get the instance of the IClient interface
	    testClient = com.dukascopy.api.system.TesterFactory.getDefaultInstance();

	    testClient.setSystemListener(new ISystemListener() {
            @Override
            public void onStart(long processId) {
                LOGGER.info("Strategy started: " + processId);
            }
            
    	    @Override
            public void onStop(long processId) {
            	SimpleDateFormat sdf;
            	Calendar calendar = Calendar.getInstance();
            	calendar .setTimeZone(TimeZone.getTimeZone("GMT"));
            	
            	sdf = new SimpleDateFormat();
            	DateFormat.getDateInstance(DateFormat.SHORT);
            	sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            	
            	LOGGER.info("Strategy stopped: " + processId);
                File reportFile = new File ( "C:\\Jforex data\\report\\Bobsley_" + calendar.getTime().getHours()
                		 + calendar.getTime().getMinutes()+ ".html" );
                try {
                	testClient.createReport(processId, reportFile);
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }
                if (testClient.getStartedStrategies().size() == 0) {
                    System.exit(0);
                }
            }

            @Override
            public void onConnect() {
                LOGGER.info("Connected");
            }

            @Override
            public void onDisconnect() {
                //tester doesn't disconnect
            }
        });
	    
	    //set the listener that will receive system events
	    
	    //testClient.setSystemListener (new MySystemListener(LOGGER, testClient, userName, password));

	    LOGGER.info ( "Connecting..." );
	    System.out.println ( "Connecting" );
	    
	    //connect to the server using jnlp, user name and password
	    testClient.connect ( jnlpUrl, userName, password );

	    //wait for it to connect
	    // This is probably useless because all of the logic to do the connection
	    // is complete by this point.
	    /*
	    for ( int i = 0; i < 10 && !testClient.isConnected(); ++i ) {
	      System.out.print ( "." );
	      Thread.sleep ( 1000 );
	    }
	    */
	    
	    if ( !testClient.isConnected() ) {
	        LOGGER.error ( "Unable to connect" );
	        System.exit ( 1 );
	    } else {
	      System.out.println ( "Connected" );
	    }

	    //subscribe to the instruments
	    Set<Instrument> instruments = new HashSet<Instrument>();
	    LOGGER.info ( "Subscribing instruments..." );

	    instruments.add (Instrument.GBPJPY);
	    testClient.setSubscribedInstruments ( instruments );

	    File cacheDir = new File ( "C:\\Jforex data\\cache" );
	    cacheDir.mkdir();
	    testClient.setCacheDirectory ( cacheDir );

	    Calendar fromDate = new GregorianCalendar();
	    Calendar toDate   = new GregorianCalendar();

	    fromDate.setTimeZone ( java.util.TimeZone.getTimeZone ( "GMT" ) );
	    fromDate.set ( 2009,    // year
	                   0,      // month
	                   1,      // day
	                   0,      // hour
	                   0 );    // min

	    toDate.setTimeZone ( java.util.TimeZone.getTimeZone ( "GMT" ) );
	    toDate.set ( 2011,      // year
	                 2,        // month
	                 1,        // day
	                 0,        // hour
	                 0 );      // min
	    
	    testClient.setDataInterval (  Period.TICK,
	                                  null,//OfferSide.BID,
	                                  null,//InterpolationMethod.FOUR_TICKS,
	                                  fromDate.getTimeInMillis(),
	                                  toDate.getTimeInMillis() );
	    testClient.setInitialDeposit ( java.util.Currency.getInstance ( "USD" ), 100000 );
	    testClient.setLeverage (100);
	    testClient.setMCEquity (0);   // this is a lower threshold.  If the equity goes below
	                                    // this value, positions/orders are closed
	    // Logging stuff
	    testClient.setProcessingStatsEnabled  ( false );
	    testClient.setEventLogEnabled         ( false );
	    testClient.setGatherReportData        ( false );

	    //start the strategy
	    LOGGER.info ( "Starting strategy" );

	    /*MaRsiStoch_v01 strategy = new MaRsiStoch_v01();
	    strategy._FixBars = 5;
	    strategy._GlobalInstrument = Instrument.EURUSD;
	    strategy._GlobalPeriod = Period.FOUR_HOURS;*/
	    
	    /*Nimy_v03 strategy = new Nimy_v03();
	    strategy._GlobalInstrument = Instrument.EURUSD;
	    strategy.OrdLots = 2;
	    strategy.AddAmounts = 4;
	    strategy.TrailStop = 20;*/
	    
	    
	    /*Martin_v05 strategy = new Martin_v05();
	    strategy._OrdLots = 1;
	    strategy._Delta = 100;
	    strategy._EndTradePeriod = 17;
	    strategy._GlobalInstrument = Instrument.EURUSD;*/
	    
	    Gap_v01_multiinstrument strategy = new Gap_v01_multiinstrument();
	    strategy._GlobalIntsr = Instrument.GBPJPY;
	    strategy._MinGapSize = 5;
	    strategy._MaxGapSize = 300;
	    strategy._MainSLKoef = 2;
	    strategy._MainTPKoef = 3;
	    
	    /*Bobsley_v01 blahstrat = new Bobsley_v01();
	    blahstrat._GlobalInstrument = Instrument.GBPJPY;
	    blahstrat._SL = 50;
	    blahstrat._TP = 40;
	    blahstrat._MAPeriod = 13;
	    blahstrat._KellyKoef = 0.1;*/
	    
	    testPID = testClient.startStrategy (strategy);
	    
	    // Do we just loop here for awhile, or what?  Based on the documentation,
	    // it sounds like startStrategy spawns a new process then returns immediately.
	    // If main() returns, will this process exit?
	  }
}
